﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Magic.Core;

/// <summary>
/// 跨域配置
/// </summary>
public static class CorsServiceCollectionExtensions
{
    public static IServiceCollection AddCors(this IServiceCollection services, IConfiguration configuration)
    {
        var allowOrigins = configuration.GetValue("AllowOrigins", "").Split(',', StringSplitOptions.RemoveEmptyEntries);

        //全开设置
        //services.AddCors(options =>
        //{
        //    options.AddDefaultPolicy(builder =>
        //    {
        //        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyMethod().AllowAnyHeader();
        //    });
        //});
        if (allowOrigins.Any())
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(allowOrigins);
                });
            });
        }
        return services;
    }
}
